package com.example.administrator.myapplication.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.example.administrator.myapplication.R;
import com.example.administrator.myapplication.bean.DrawBean;
import com.example.administrator.myapplication.enums.PenType;

import java.util.ArrayList;
import java.util.Iterator;


public class MyDrawView extends View implements DrawViewInterface {
    //画笔的颜色
    private int paintColor;
    //画笔的宽度
    private int paintWith;
    private boolean isReDraw = false;
    private int state;
    private boolean isFirst = true;
    private Bitmap mBottomBitmap=null;
    private Canvas mCanvas=null;
    private Paint bitmapPaint=new Paint();
    private float posX,posY;
    private final float TOUCH_TOLERANCE = 5;
    //路径的集合
    private ArrayList<DrawBean> drawList;
    //用来撤销和恢复的集合
    private ArrayList<DrawBean> undoList;
    //当前的路径
    private Path mPath;
    //当前的画笔
    private Paint mPaint;
    //荧光笔的中间的白色画笔
    private Paint whitePaint;

    public MyDrawView(Context context) {
        super(context);
        init();
    }

    public MyDrawView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MyDrawView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mBottomBitmap=Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_8888);
        mCanvas=new Canvas(mBottomBitmap);
    }

    private void init() {
        debug("init");
        paintColor = R.color.colorRed;
        paintWith = 10;
        whitePaint = new Paint();
        whitePaint.setStyle(Paint.Style.STROKE);
        whitePaint.setColor(getColor(R.color.colorWhite));
        whitePaint.setStrokeWidth(paintWith);
        //让连接处圆滑
        whitePaint.setStrokeJoin(Paint.Join.ROUND);
        //让笔触圆滑
        whitePaint.setStrokeCap(Paint.Cap.ROUND);
        whitePaint.setAntiAlias(true);
        drawList = new ArrayList<>();
        undoList = new ArrayList<>();
        // 设置常亮
        this.setKeepScreenOn(true);

    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPaint = getHightlightPaint();
                mPath = new Path();
                mPath.moveTo(x, y);
                state = MotionEvent.ACTION_DOWN;
                posX=x;
                posY=y;
//                postInvalidate();
                break;
            case MotionEvent.ACTION_MOVE:
                float dx = Math.abs(x - posX);
                float dy = Math.abs(y - posY);
                if(dx >= TOUCH_TOLERANCE || dy > TOUCH_TOLERANCE)
                {
                    mPath.quadTo(posX, posY, (x + posX)/2, (y + posY)/2);
                    posX = x;
                    posY = y;
                }
                state = MotionEvent.ACTION_MOVE;
                postInvalidate();
                break;
            case MotionEvent.ACTION_UP:
                saveDraw(mPaint, mPath);
                mCanvas.drawPath(mPath,mPaint);
                mCanvas.drawPath(mPath,whitePaint);
                mPath = null;
                mPaint = null;
                state = MotionEvent.ACTION_UP;
                postInvalidate();
                break;
        }
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
            canvas.drawColor(getColor(R.color.colorWhite));
//            synchronized (drawList) {
//                Iterator<DrawBean> iterator = drawList.iterator();
//                while (iterator.hasNext()) {
//                    DrawBean drawBean = iterator.next();
//                    canvas.drawPath(drawBean.getmPath(), drawBean.getmPaint());
//                    canvas.drawPath(drawBean.getmPath(), whitePaint);
//                }
//            }

        canvas.drawBitmap(mBottomBitmap,0,0,bitmapPaint);
        if (mPaint != null && mPath != null) {
            canvas.drawPath(mPath, mPaint);
            canvas.drawPath(mPath, whitePaint);
        }

    }

    private void reDraw(){
        synchronized (drawList) {
            mCanvas.drawColor(getColor(R.color.colorWhite));
                Iterator<DrawBean> iterator = drawList.iterator();
                while (iterator.hasNext()) {
                    DrawBean drawBean = iterator.next();
                    mCanvas.drawPath(drawBean.getmPath(), drawBean.getmPaint());
                    mCanvas.drawPath(drawBean.getmPath(), whitePaint);
                }
        }
    }

    private Paint getHightlightPaint() {
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(getResources().getColor(paintColor));
        //图片填充画笔
//        Bitmap bitmap= BitmapFactory.decodeResource(getContext().getResources(),R.drawable.banana);
//        paint.setShader(new BitmapShader(bitmap, Shader.TileMode.REPEAT,Shader.TileMode.REPEAT));
        paint.setStrokeWidth(paintWith + 30);
        //让连接处圆滑
        paint.setMaskFilter(new BlurMaskFilter(50f, BlurMaskFilter.Blur.NORMAL));
        paint.setStrokeJoin(Paint.Join.ROUND);
        //让笔触圆滑
        paint.setStrokeCap(Paint.Cap.ROUND);
//        paint.setAlpha(180);
//        paint.setShader(new RadialGradient(100f,100f,20f,Color.WHITE,Color.RED,Shader.TileMode.CLAMP));
        return paint;
    }


    @Override
    public void undo() {
        synchronized (drawList) {
            if (drawList.size() <= 0) {
                return;
            }
            DrawBean drawBean = drawList.get(drawList.size() - 1);
            undoList.add(drawBean);
            drawList.remove(drawBean);
        }
        reDraw();
        postInvalidate();
    }

    @Override
    public void advance() {
        synchronized (drawList) {
            if (undoList.size() <= 0) {
                return;
            }
            DrawBean drawBean = undoList.get(undoList.size() - 1);
            drawList.add(drawBean);
            undoList.remove(drawBean);
        }
        reDraw();
        postInvalidate();
    }

    /**
     * 保存路径和画笔
     */
    private void saveDraw(Paint paint, Path path) {
        //为了线程安全，加锁
        synchronized (drawList) {
            drawList.add(new DrawBean(paint, path, PenType.HIGHLIGHT));
            undoList.clear();
        }
    }

    private int getColor(int id) {
        return getContext().getResources().getColor(id);
    }

    private void debug(String log) {
        Log.i("zcj", log);
    }
}

